package com.sjm.bookshop.email;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.sjm.bookshop.utils.MD5Util;
import com.sjm.bookshop.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/email")
public class EmailUtil {

    @Autowired
    private EmailService emailService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送简单邮件
     *
     * @return
     */
    @RequestMapping("/mail")
    public Result sendMail() {
//        构建一个邮件对象
        SimpleMailMessage mailMessage = new SimpleMailMessage();
//        设置邮件主题
        mailMessage.setSubject("图书商城");
//        设置邮件发送者
        mailMessage.setFrom("2451375713@qq.com");
//        设置邮件接收者，可以有多个，中间用都好隔开
//        mailMessage.setTo("xx@qq.com","xx@qq.com");
        mailMessage.setTo("2802902358@qq.com");
//        设置邮件的发送日期
        mailMessage.setSentDate(new Date());
//        邮件正文
        mailMessage.setText("这是邮件测试的正文");
//        发送邮件
        javaMailSender.send(mailMessage);
        return Result.success(200, "success");
    }

    /**
     * 发送富文本邮件
     */

    @RequestMapping("/mutEmail")
    public Result sendMimeMail(String phone, String email) throws MessagingException {
//        做一个正则判断
        if (!phone.equals(null) && !email.equals(null)) {
//            邮箱发送验证码次数判断
            boolean flag = emailService.verifyEmail(phone, email);
            if (flag) {
                return Result.success(200, "邮件已发送");
            } else {
                return Result.fail(201, "邮件发送已达3次,请明天再尝试！");
            }

        } else {
            return Result.fail(202, "邮箱或手机号错误！！！");
        }
    }


    //    忘记密码
    @RequestMapping("/getCode")
    public Result getCode(String phone) {
        ValueOperations ops = redisTemplate.opsForValue();
        // 生成图片验证码类
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 36);
        // 获取图片验证码上的字符串(小写)
        String lowerCaseCode = captcha.getCode().toLowerCase();
        System.out.println("lowerCaseCode---" + lowerCaseCode);
        // 转化为base64f给前端
        String imageBase = captcha.getImageBase64();
        // 将字符串用md5加密当作key保存到redis中
        String md5Image = DigestUtils.md5DigestAsHex(lowerCaseCode.getBytes());
        // 保存到redis中，userKey为keyname，设置过期时间为2分钟
        String userKey = "verifyCode:" + phone;
        ops.set(userKey, md5Image, 2, TimeUnit.MINUTES);
        // 下次前端携带此参数我们从redis中查询
//        hashMap.put("md5Image", md5Image);
        return Result.success(200, imageBase, "切换成功");
    }

    /**
     * 重设密码
     */
    @RequestMapping("/resetPwd")
    public Result resetPwd(String phone, String password, String code) {

        if(phone!=null&&password!=null && code != null){
            ValueOperations ops = redisTemplate.opsForValue();
            String getKey = "verifyCode:" + phone;
            String redisKey = ops.get(getKey).toString();
            String formKey = DigestUtils.md5DigestAsHex(code.getBytes());
            System.out.println(phone + "---" + password + "---" + code + "formkey::" + formKey + "redisKey" + redisKey);
            if (redisKey.equals(formKey)) {
               int result = emailService.updateAdminPwd(phone, MD5Util.MD5(password));
               if (result > 0){
                   return Result.success(200, "修改密码成功");
               }else{
                   return Result.fail(201, "修改失败");
               }
            } else {
                return Result.fail(201, "验证码错误");
            }
        }else {
            return Result.fail(202, "请求错误");
        }


    }
}
